using Digitalmes.Application.Mes.Traceability.Products;
using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Traceability.Workstations.Queries;

/// <summary>
/// 分页查询产品在指定工位上的生产工艺步骤查询命令。
/// </summary>
/// <param name="LineId">产线 Id</param>
/// <param name="WorkstationId">查询工位 Id</param>
/// <param name="ProductId">查询产品 Id</param>
/// <param name="Result">过站状态，OK/NG</param>
/// <param name="StartTime">过站查询开始时间</param>
/// <param name="EndTime">过站查询结束时间</param>
public sealed record GetProcessStepListWithPagedQuery(
    long LineId,
    long WorkstationId,
    long? ProductId,
    string? Result,
    DateTime? StartTime,
    DateTime? EndTime,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProdStepExecutionDto>>>;

internal sealed class GetProcessStepListWithPagedQueryHandler(IRepository<ProdStepExecution> stepExecutionRepo) : IRequestHandler<GetProcessStepListWithPagedQuery, IResult<PagedList<ProdStepExecutionDto>>>
{
    public async Task<IResult<PagedList<ProdStepExecutionDto>>> Handle(GetProcessStepListWithPagedQuery request, CancellationToken cancellationToken)
    {
        // 查找执行记录（可重复过站）
        var items = await stepExecutionRepo
            .AsQueryable()
            .WhereIF(request.ProductId > 0, m => m.ProductId == request.ProductId)
            .WhereIF(request.StartTime != null, m => m.OutboundTime >= request.StartTime.MinTime())
            .WhereIF(request.EndTime != null, m => m.OutboundTime <= request.EndTime.MaxTime())
            .WhereIF(request.Result == "OK", m => m.PassResult == PassEnum.OK || m.PassResult == PassEnum.ForceOK)
            .WhereIF(request.Result == "NG", m => m.PassResult == PassEnum.NG || m.PassResult == PassEnum.ForceNG)
            .Where(m => m.LineId == request.LineId && m.WorkstationId == request.WorkstationId)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ProdStepExecutionDto>>());
    }
}
